package project02.controller.mobile.login;

import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.util.BeanUtil;

import project02.cool.Util;
import project02.dao.UserInfoDao;
import project02.model.UserInfo;

public class Reg02Controller extends Controller {

    private Util util = Util.getInstance();
    private UserInfoDao dao = new UserInfoDao();

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(Reg02Controller.class.getName());

    @SuppressWarnings("null")
    @Override
    public Navigation run() {

        String iModeId = "";
        iModeId = request.getHeader("x-dcmguid");
        requestScope("iModeId", iModeId);

        if (!Validate()) {
            return forward("reg01.jsp");
        }

        try {
            if (util.chkUserId(asString("userId"))) {
                requestScope("mobileMsg", "このユーザIDはすでに使用されています.");
                return forward("reg01.jsp");
            }
        } catch (Exception e) {
            requestScope("mobileMsg", "このユーザIDはすでに使用されています." + e);
            return forward("reg01.jsp");
        }

        try {
            if (util.chkImodeId(asString("userAccount"))) {
                requestScope("mobileMsg", "この携帯電話はすでに登録されています.");
                return forward("reg01.jsp");
            }
        } catch (Exception e) {
            requestScope("mobileMsg", "この携帯電話はすでに登録されています." + e);
            return forward("reg01.jsp");
        }


        UserInfo u = new UserInfo();
        UserInfo result = new  UserInfo();

        BeanUtil.copy(request, u);

        try {
            result = dao.makePersistentInTx(u);
        } catch (Exception e) {
            requestScope("mobileMsg", "登録ができませんでした." + asString("userId") + e);
            return forward("reg01.jsp");
        }
        if (result != null || result.getUserId().equals(u.getUserId())) {
            requestScope("mobileMsg", "登録が完了しました.");
            return forward("/mobile/index.jsp");
        } else {
            requestScope("mobileMsg", "登録ができませんでした.");
        }

        return forward("reg01.jsp");

    }

    private boolean Validate() {

        Validators val = new Validators(request);
        val.add("userId", val.required());
        val.add("password", val.required());
        val.add("userName", val.required());
        val.add("userNameKana", val.required());
        return val.validate();
    }
}
